using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Hotel.UI.Common
{
    /// <summary>
    /// 获取网页数据辅助类库。
    /// </summary>
    public class HttpHelper
    {
        private System.Net.CookieContainer cookieContainer;

        private string contentType;

        private string accept;

        private string userAgent;

        private System.Text.Encoding encoding;

        private int networkDelay;

        private int maxTry;

        private int currentTry;

        /// <summary>
        /// Accept值，默认支持各种类型
        /// </summary>
        public string Accept
        {
            get
            {
                return this.accept;
            }
            set
            {
                this.accept = value;
            }
        }

        /// <summary>
        /// X509Certificate2证书集合
        /// </summary>
        public X509CertificateCollection ClientCertificates
        {
            get;
            set;
        }

        /// <summary>
        /// 内容类型，默认为"application/x-www-form-urlencoded"
        /// </summary>
        public string ContentType
        {
            get
            {
                return this.contentType;
            }
            set
            {
                this.contentType = value;
            }
        }

        /// <summary>
        /// Cookie容器
        /// </summary>
        public System.Net.CookieContainer CookieContainer
        {
            get
            {
                return this.cookieContainer;
            }
        }

        /// <summary>
        /// 获取网页源码时使用的编码
        /// </summary>
        /// <value></value>
        public System.Text.Encoding Encoding
        {
            get
            {
                return this.encoding;
            }
            set
            {
                this.encoding = value;
            }
        }

        /// <summary>
        /// 最大尝试次数
        /// </summary>
        public int MaxTry
        {
            get
            {
                return this.maxTry;
            }
            set
            {
                this.maxTry = value;
            }
        }

        /// <summary>
        /// 网络延时
        /// </summary>
        public int NetworkDelay
        {
            get
            {
                Random random = new Random();
                int num = random.Next(this.networkDelay / 0x3e8, this.networkDelay / 0x3e8 * 2) * 0x3e8;
                return num;
            }
            set
            {
                this.networkDelay = value;
            }
        }

        /// <summary>
        /// UserAgent，默认支持Mozilla/MSIE等
        /// </summary>
        public string UserAgent
        {
            get
            {
                return this.userAgent;
            }
            set
            {
                this.userAgent = value;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpHelper()
        {

            this.contentType = "application/x-www-form-urlencoded";
            this.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            this.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            this.encoding = System.Text.Encoding.GetEncoding("utf-8");
            this.networkDelay = 0x3e8;
            this.maxTry = 3;
            this.currentTry = 0;

            this.cookieContainer = new System.Net.CookieContainer();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cc">指定CookieContainer的值</param>
        public HttpHelper(System.Net.CookieContainer cc)
        {

            this.contentType = "application/x-www-form-urlencoded";
            this.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            this.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            this.encoding = System.Text.Encoding.GetEncoding("utf-8");
            this.networkDelay = 0x3e8;
            this.maxTry = 3;
            this.currentTry = 0;

            this.cookieContainer = cc;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contentType">内容类型</param>
        /// <param name="accept">Accept类型</param>
        /// <param name="userAgent">UserAgent内容</param>
        public HttpHelper(string contentType, string accept, string userAgent)
        {

            this.contentType = "application/x-www-form-urlencoded";
            this.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            this.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            this.encoding = System.Text.Encoding.GetEncoding("utf-8");
            this.networkDelay = 0x3e8;
            this.maxTry = 3;
            this.currentTry = 0;

            this.contentType = contentType;
            this.accept = accept;
            this.userAgent = userAgent;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cc">指定CookieContainer的值</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="accept">Accept类型</param>
        /// <param name="userAgent">UserAgent内容</param>
        public HttpHelper(System.Net.CookieContainer cc, string contentType, string accept, string userAgent)
        {

            this.contentType = "application/x-www-form-urlencoded";
            this.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            this.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            this.encoding = System.Text.Encoding.GetEncoding("utf-8");
            this.networkDelay = 1000;
            this.maxTry = 3;
            this.currentTry = 0;

            this.cookieContainer = cc;
            this.contentType = contentType;
            this.accept = accept;
            this.userAgent = userAgent;
        }

        /// <summary>
        /// 根据Cookie字符串获取Cookie的集合
        /// </summary>
        /// <param name="cookieString">Cookie字符串</param>
        /// <returns></returns>
        public CookieCollection GetCookieCollection(string cookieString)
        {
            CookieCollection cookieCollections = new CookieCollection();
            foreach (System.Text.RegularExpressions.Match match in (new Regex("([^;,]+)=([^;,]+);Domain=([^;,]+);Path=([^;,]+)", RegexOptions.IgnoreCase)).Matches(cookieString))
            {
                Cookie cookie = new Cookie(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, match.Groups[3].Value);
                cookieCollections.Add(cookie);
            }
            return cookieCollections;
        }

        /// <summary>
        /// 获取网页的编码格式
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <returns></returns>
        public string GetEncoding(string url)
        {
            string value;
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse response = null;
            StreamReader streamReader = null;
            try
            {
                try
                {
                    httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                    httpWebRequest.Timeout = 0x4e20;
                    httpWebRequest.AllowAutoRedirect = false;
                    response = (HttpWebResponse)httpWebRequest.GetResponse();
                    if ((response.StatusCode != HttpStatusCode.OK ? false : response.ContentLength < 0x100000L))
                    {
                        streamReader = ((response.ContentEncoding == null ? true : !response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) ? new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII) : new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)));
                        string end = streamReader.ReadToEnd();
                        Regex regex = new Regex("charset\\b\\s*=\\s*(?<charset>[^\"]*)");
                        if (regex.IsMatch(end))
                        {
                            value = regex.Match(end).Groups["charset"].Value;
                            return value;
                        }
                        else if (response.CharacterSet == string.Empty)
                        {
                            value = System.Text.Encoding.Default.BodyName;
                            return value;
                        }
                        else
                        {
                            value = response.CharacterSet;
                            return value;
                        }
                    }
                }
                catch
                {
                }
                value = System.Text.Encoding.Default.BodyName;
                return value;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (httpWebRequest != null)
                {
                    httpWebRequest = null;
                }
            }
            return value;
        }

        /// <summary>
        /// 获取HTML页面内容指定隐藏域Key的Value内容
        /// </summary>
        /// <param name="html">待操作的HTML页面内容</param>
        /// <param name="key">隐藏域的名称</param>
        /// <returns></returns>
        public string GetHiddenKeyValue(string html, string key)
        {
            string value = "";
            string str = string.Format("<input\\s*type=\"hidden\".*?name=\"{0}\".*?\\s*value=[\"|'](?<value>.*?)[\"|'^/]", key);
            System.Text.RegularExpressions.Match match = (new Regex(str, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace)).Match(html);
            if (match.Success)
            {
                value = match.Groups[1].Value;
            }
            return value;
        }

        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="cookieContainer">Cookie集合</param>
        /// <param name="postData">回发的数据</param>
        /// <param name="isPost">是否以post方式发送请求</param>
        /// <returns></returns>
        public string GetHtml(string url, System.Net.CookieContainer cookieContainer, string postData, bool isPost)
        {
            return this.GetHtml(url, cookieContainer, postData, isPost, url);
        }

        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="cookieContainer">Cookie集合对象</param>
        /// <param name="postData">回发的数据</param>
        /// <param name="isPost">是否以post方式发送请求</param>
        /// <param name="referer">页面引用</param>
        /// <returns></returns>
        public string GetHtml(string url, System.Net.CookieContainer cookieContainer, string postData, bool isPost, string referer)
        {
            string empty;
            HttpWebResponse response;
            if (!string.IsNullOrEmpty(postData))
            {
                HttpHelper httpHelper = this;
                httpHelper.currentTry = httpHelper.currentTry + 1;
                try
                {
                    byte[] bytes = this.Encoding.GetBytes(postData);
                    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                    httpWebRequest.CookieContainer = cookieContainer;
                    httpWebRequest.ContentType = this.contentType;
                    httpWebRequest.Referer = referer;
                    httpWebRequest.Accept = this.accept;
                    httpWebRequest.UserAgent = this.userAgent;
                    httpWebRequest.Method = (isPost ? "POST" : "GET");
                    httpWebRequest.ContentLength = bytes.Length;
                    httpWebRequest.AllowAutoRedirect = false;
                    if (this.ClientCertificates != null)
                    {
                        foreach (X509Certificate clientCertificate in this.ClientCertificates)
                        {
                            httpWebRequest.ClientCertificates.Add(clientCertificate);
                        }
                    }

                    Stream requestStream = httpWebRequest.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();

                    try
                    {
                        response = (HttpWebResponse)httpWebRequest.GetResponse();
                    }
                    catch (WebException webException)
                    {
                        response = (HttpWebResponse)webException.Response;
                    }
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream, this.encoding);
                    string end = streamReader.ReadToEnd();
                    streamReader.Close();
                    responseStream.Close();
                    this.currentTry = 0;
                    empty = end;
                }
                catch (Exception exception)
                {
                    if (this.currentTry <= this.maxTry)
                    {
                        this.GetHtml(url, cookieContainer, postData, isPost);
                    }
                    this.currentTry = 0;
                    empty = string.Empty;
                }
            }
            else
            {
                CookieCollection cookieCollections = new CookieCollection();
                empty = this.GetHtml(url, cookieContainer, referer);
            }
            return empty;
        }
        public string HttpGet(string Url, string postDataStr)
        {
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
                httpWebRequest.Method = "GET";
                httpWebRequest.ContentType = this.contentType;
                HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, this.encoding);
                 string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="cookieContainer">Cookie集合</param>
        /// <param name="reference">页面引用</param>
        /// <returns></returns>
        public string GetHtml(string url, System.Net.CookieContainer cookieContainer, string reference)
        {
            string empty;
            HttpHelper int2 = this;
            int2.currentTry = int2.currentTry + 1;
            try
            {
                System.GC.Collect();
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = this.contentType;
                httpWebRequest.Referer = reference;
                httpWebRequest.Accept = this.accept;
                httpWebRequest.UserAgent = this.userAgent;
                httpWebRequest.Method = "GET";
                if (this.ClientCertificates != null)
                {
                    foreach (X509Certificate clientCertificate in this.ClientCertificates)
                    {
                        httpWebRequest.ClientCertificates.Add(clientCertificate);
                    }
                }
                Stream responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, this.encoding);
                string end = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                this.currentTry = 0;
                empty = end;
            }
            catch (Exception exception)
            {
                if (this.currentTry <= this.maxTry)
                {
                    this.GetHtml(url, cookieContainer, reference);
                }
                this.currentTry = 0;
                empty = string.Empty;
            }
            return empty;
        }

        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <returns></returns>
        public string GetHtml(string url)
        {
            return this.GetHtml(url, this.cookieContainer, null);
        }

        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="reference">页面引用</param>
        /// <returns></returns>
        public string GetHtml(string url, string reference)
        {
            return this.GetHtml(url, this.cookieContainer, reference);
        }

        /// <summary>
        /// 获取指定页面的HTML代码
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="postData">回发的数据</param>
        /// <param name="isPost">是否以post方式发送请求</param>
        /// <returns></returns>
        public string GetHtml(string url, string postData, bool isPost)
        {
            return this.GetHtml(url, this.cookieContainer, postData, isPost, "");
        }

        /// <summary>
        /// 获取指定页面的Stream
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="cookieContainer">Cookie集合对象</param>
        /// <returns></returns>
        public Stream GetStream(string url, ref string fileName, System.Net.CookieContainer cookieContainer)
        {
            return this.GetStream(url, ref fileName, cookieContainer, url);
        }

        /// <summary>
        /// 获取指定页面的Stream
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="cookieContainer">Cookie对象</param>
        /// <param name="reference">页面引用</param>
        public Stream GetStream(string url, ref string fileName, System.Net.CookieContainer cookieContainer, string reference)
        {
            Stream stream;
            string str;
            HttpHelper int2 = this;
            int2.currentTry = int2.currentTry + 1;
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = this.contentType;
                httpWebRequest.Referer = reference;
                httpWebRequest.Accept = this.accept;
                httpWebRequest.UserAgent = this.userAgent;
                httpWebRequest.Method = "GET";
                if (this.ClientCertificates != null)
                {
                    foreach (X509Certificate clientCertificate in this.ClientCertificates)
                    {
                        httpWebRequest.ClientCertificates.Add(clientCertificate);
                    }
                }
                HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (response.Headers["Content-Disposition"] != null)
                {
                    str = response.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "");
                }
                else if (response.Headers["Location"] != null)
                {
                    str = Path.GetFileName(response.Headers["Location"]);
                }
                else if (Path.GetFileName(url).Contains("="))
                {
                    str = url.Substring(url.LastIndexOf("=") + 1);
                }
                else
                {
                    str = (Path.GetFileName(url).Contains("?") ? url.Substring(url.LastIndexOf("?") + 1) : Path.GetFileName(response.ResponseUri.ToString()));
                }
                fileName = str;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = "UnKnowFileName";
                }
                else
                {
                    fileName = Path.GetFileName(fileName);
                }
                this.currentTry = 0;
                stream = responseStream;
            }
            catch (Exception exception)
            {
                if (this.currentTry <= this.maxTry)
                {
                    CookieCollection cookieCollections = new CookieCollection();
                    this.GetStream(url, ref fileName, cookieContainer, reference);
                }
                this.currentTry = 0;
                stream = null;
            }
            return stream;
        }

        public Stream GetStream(string url, ref string fileName, System.Net.CookieContainer cookieContainer, string postData, bool isPost, string reference)
        {
            Stream stream;
            string str;
            HttpHelper int2 = this;
            int2.currentTry = int2.currentTry + 1;
            try
            {
                byte[] bytes = this.Encoding.GetBytes(postData);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = this.contentType;
                httpWebRequest.Referer = reference;
                httpWebRequest.Accept = this.accept;
                httpWebRequest.UserAgent = this.userAgent;
                httpWebRequest.Method = (isPost ? "POST" : "GET");
                if (this.ClientCertificates != null)
                {
                    foreach (X509Certificate clientCertificate in this.ClientCertificates)
                    {
                        httpWebRequest.ClientCertificates.Add(clientCertificate);
                    }
                }
                Stream requestStream = httpWebRequest.GetRequestStream();
                requestStream.Write(bytes, 0, (int)bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (response.Headers["Content-Disposition"] != null)
                {
                    str = response.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "");
                }
                else if (response.Headers["Location"] != null)
                {
                    str = Path.GetFileName(response.Headers["Location"]);
                }
                else if (Path.GetFileName(url).Contains("="))
                {
                    str = url.Substring(url.LastIndexOf("=") + 1);
                }
                else
                {
                    str = (Path.GetFileName(url).Contains("?") ? url.Substring(url.LastIndexOf("?") + 1) : Path.GetFileName(response.ResponseUri.ToString()));
                }
                fileName = str;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = "UnKnowFileName";
                }
                else
                {
                    fileName = Path.GetFileName(fileName);
                }
                this.currentTry = 0;
                stream = responseStream;
            }
            catch (Exception exception)
            {
                if (this.currentTry <= this.maxTry)
                {
                    CookieCollection cookieCollections = new CookieCollection();
                    this.GetStream(url, ref fileName, cookieContainer, postData, isPost, reference);
                }
                this.currentTry = 0;
                stream = null;
            }
            return stream;
        }

        /// <summary>
        /// 判断URL是否有效
        /// </summary>
        /// <param name="url">待判断的URL，可以是网页以及图片链接等</param>
        /// <returns>200为正确，其余为大致网页错误代码</returns>
        public int GetUrlError(string url)
        {
            int num;
            int num1 = 200;
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                ServicePointManager.Expect100Continue = false;
                ((HttpWebResponse)httpWebRequest.GetResponse()).Close();
            }
            catch (WebException webException1)
            {
                WebException webException = webException1;
                if (webException.Status != WebExceptionStatus.ProtocolError)
                {
                    num = num1;
                    return num;
                }
                else if (webException.Message.IndexOf("500 ") > 0)
                {
                    num = 0x1f4;
                    return num;
                }
                else if (webException.Message.IndexOf("401 ") > 0)
                {
                    num = 0x191;
                    return num;
                }
                else if (webException.Message.IndexOf("404") > 0)
                {
                    num1 = 0x194;
                }
            }
            catch
            {
                num1 = 0x191;
            }
            num = num1;
            return num;
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="inputData">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);
        }

        public static NameValueCollection ParseUrl(string url, out string baseUrl)
        {
            NameValueCollection nameValueCollection;
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            NameValueCollection nameValueCollection1 = new NameValueCollection();
            baseUrl = "";
            if (url != "")
            {
                int num = url.IndexOf('?');
                if (num != -1)
                {
                    baseUrl = url.Substring(0, num);
                    if (num != url.Length - 1)
                    {
                        string str = url.Substring(num + 1);
                        foreach (System.Text.RegularExpressions.Match match in (new Regex("(^|&)?(\\w+)=([^&]+)(&|$)?", RegexOptions.Compiled)).Matches(str))
                        {
                            nameValueCollection1.Add(match.Result("$2").ToLower(), match.Result("$3"));
                        }
                        nameValueCollection = nameValueCollection1;
                    }
                    else
                    {
                        nameValueCollection = nameValueCollection1;
                    }
                }
                else
                {
                    baseUrl = url;
                    nameValueCollection = nameValueCollection1;
                }
            }
            else
            {
                nameValueCollection = nameValueCollection1;
            }
            return nameValueCollection;
        }

        /// <summary>
        /// 提交文件流到服务地址
        /// </summary>
        /// <param name="url">指定页面的路径</param>
        /// <param name="files">提交的文件列表</param>
        /// <param name="nvc">其他内容（名称-值键值）</param>
        /// <param name="cookieContainer">Cookie对象</param>
        /// <param name="reference">页面引用</param>
        /// <returns></returns>
        public string PostStream(string url, string[] files, NameValueCollection nvc = null, System.Net.CookieContainer cookieContainer = null, string reference = null)
        {
            long ticks = DateTime.Now.Ticks;
            string str = string.Concat("----------------------------", ticks.ToString("x"));
            HttpWebRequest defaultCredentials = (HttpWebRequest)WebRequest.Create(url);
            defaultCredentials.ContentType = string.Concat("multipart/form-data; boundary=", str);
            defaultCredentials.Method = "POST";
            defaultCredentials.KeepAlive = true;
            defaultCredentials.Credentials = CredentialCache.DefaultCredentials;
            defaultCredentials.CookieContainer = cookieContainer;
            defaultCredentials.Referer = reference;
            if (this.ClientCertificates != null)
            {
                foreach (X509Certificate clientCertificate in this.ClientCertificates)
                {
                    defaultCredentials.ClientCertificates.Add(clientCertificate);
                }
            }
            Stream memoryStream = new MemoryStream();
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string.Concat("\r\n--", str, "\r\n"));
            string str1 = string.Concat("\r\n--", str, "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}");
            if (nvc != null)
            {
                foreach (string key in nvc.Keys)
                {
                    string str2 = string.Format(str1, key, nvc[key]);
                    byte[] numArray = this.Encoding.GetBytes(str2);
                    memoryStream.Write(numArray, 0, (int)numArray.Length);
                }
            }
            memoryStream.Write(bytes, 0, (int)bytes.Length);
            string str3 = "media";
            string str4 = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
            if (files != null)
            {
                for (int i = 0; i < (int)files.Length; i++)
                {
                    string name = (new FileInfo(files[i])).Name;
                    string str5 = string.Format(str4, str3, name);
                    byte[] bytes1 = this.Encoding.GetBytes(str5);
                    memoryStream.Write(bytes1, 0, (int)bytes1.Length);
                    FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read);
                    byte[] numArray1 = new byte[0x400];
                    int num = 0;
                    while (true)
                    {
                        int num1 = fileStream.Read(numArray1, 0, (int)numArray1.Length);
                        num = num1;
                        if (num1 == 0)
                        {
                            break;
                        }
                        memoryStream.Write(numArray1, 0, num);
                    }
                    memoryStream.Write(bytes, 0, (int)bytes.Length);
                    fileStream.Close();
                }
            }
            defaultCredentials.ContentLength = memoryStream.Length;
            Stream requestStream = defaultCredentials.GetRequestStream();
            try
            {
                memoryStream.Position = 0L;
                byte[] numArray2 = new byte[(memoryStream.Length)];
                memoryStream.Read(numArray2, 0, (int)numArray2.Length);
                memoryStream.Close();
                requestStream.Write(numArray2, 0, (int)numArray2.Length);
                requestStream.Close();
            }
            finally
            {
                if (requestStream != null)
                {
                    ((IDisposable)requestStream).Dispose();
                }
            }
            string end = null;
            WebResponse response = defaultCredentials.GetResponse();
            try
            {
                Stream responseStream = response.GetResponseStream();
                try
                {
                    StreamReader streamReader = new StreamReader(responseStream);
                    try
                    {
                        end = streamReader.ReadToEnd();
                    }
                    finally
                    {
                        if (streamReader != null)
                        {
                            ((IDisposable)streamReader).Dispose();
                        }
                    }
                }
                finally
                {
                    if (responseStream != null)
                    {
                        ((IDisposable)responseStream).Dispose();
                    }
                }
            }
            finally
            {
                if (response != null)
                {
                    ((IDisposable)response).Dispose();
                }
            }
            defaultCredentials = null;
            return end;
        }

        /// <summary>
        /// 移除Html标记
        /// </summary>
        public string RemoveHtml(string content)
        {
            return Regex.Replace(content, "<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }
    }
}